<template>
<div 
    class="select-baidusug-cp"
    @click.stop
    v-show="dataList.length>0">
    <MyTabsSlot
        class="container">
        <div 
            :class="{
                'item':true,
                'title-after':currentIndex==index,
            }"
            v-for="(item,index) in dataList" :key="index"
            @click="onClickItem(item)">
            {{item}}
        </div>
    </MyTabsSlot>
    <span class="help">
        'Ctrl' + '↑ ↓' 选择
    </span>
</div>
</template>

<script>
/*
 选择百度建议词条组件
 */
import MyTabsSlot from "@/components/MyTabsSlot";
import {throttleFn} from '@/common/DebounceAndThrottle';
export default {
    name: 'SelectBaiduSug',
    components:{MyTabsSlot},
    props:{
        keyWord:{   //需要搜索的关键字
            type:String,
            default:'',
        },
        engine:{  //搜索引擎
            type:Object,
            default:()=>{
                return {};
            },
        },
    },
    data(){
        return {
            dataList:[], //建议词条列表
            currentIndex:-1, //已选中的网站索引(默认没选中)
        };
    },
    created(){
        this.initEvent(); //添加键盘监听
    },
    watch:{
        currentIndex(newValue){ //当索引改变时触发改变事件，暴露当前选择的sug
            this.$emit('onChange',{
                currentIndex:newValue,
                currentData:this.dataList[newValue],
            });
        },
        keyWord:{ //监听搜索数据，发生变化时请求百度建议词条
            handler(newValue){
                this.getBaiduSug(newValue);
            },
            immediate:true,
        },
    },
    methods:{
        initCurrentIndex(currentIndex=-1){  //初始化数据（外部调用）
            this.currentIndex = currentIndex;
        },
        initDataList(dataList=[]){  //初始化数据（外部调用）
            this.dataList = dataList;
        },
        getBaiduSug:throttleFn(function(str){
            this.currentIndex = -1;  //值发生变化时就清空当前选项
            window.baidu = {
                sug: (json)=>{ //初始化一个回调函数
                    this.dataList=json.s;
                }
            }
            if(str){
                let sug=document.createElement('script');
                sug.src=`https://suggestion.baidu.com/su?wd=${str}&cb=window.baidu.sug`;
                document.getElementsByTagName('body')[0].appendChild(sug);
            }else{ //值为空时清空数据
                this.dataList=[];
            }
        },150),
        onClickItem(item){
            //获得当前搜索引擎进行拼接后跳转
            let engine = this.engine.search || '';
            engine = engine.replace("{searchData}",encodeURI(item));
            window.open(engine);
        },
        initEvent(){ //初始化键盘按钮事件
            window.addEventListener('keydown',(event)=>{
                const e = event || window.event || arguments.callee.caller.arguments[0];
                if(!e) return false;
                //当组件隐藏时不选择
                if(this.dataList.length==0) return false;
                //选择建议词条必须ctrl加上下键(避免按动enter键时清空建议词条)
                if(e.shiftKey || e.altKey) return false;
                if(!e.ctrlKey && (e.keyCode == 38 || e.keyCode == 40)) return false;
                if(!this.isActive()) return false;
                switch(e.keyCode){
                    case 38: //上
                        this.upKeyDown();
                        break;
                    case 40: //下
                        this.downKeyDown();
                        break;
                }
                return false;
            });
        },
        upKeyDown(){ //键盘上键按下执行
            let length = this.dataList.length;
            if (length==0) return;
            let newIndex = this.currentIndex-1;
            if (newIndex<-1){ //选择时留个空位
                this.currentIndex = length-1;
            }else{
                this.currentIndex = newIndex;
            }
        },
        downKeyDown(){ //键盘下键按下执行
            let length = this.dataList.length;
            if (length==0) return;
            let newIndex = this.currentIndex+1;
            if (newIndex>length){ //选择时留个空位
                this.currentIndex = 0;
            }else{
                this.currentIndex = newIndex;
            }
        },
        isActive(){  //是否是当前活动的组件
            const el = this.$el;
            if(!el) return false;
            return !!(el.clientWidth || el.clientHeight);
        },
    },
}
</script>
<style lang="scss" scoped>
@media only screen and (min-width: 1920px){
    .container{
        padding: 0.5rem 1rem;
        max-height: 15rem;
        >.item{
            margin: 0.45rem 1.2rem 0.45rem 0;
            font-size: 2rem;
        }
    }
}
@media only screen and (max-width: 1920px){
    .container{
        padding: 4px 8px;
        max-height: 100px;
        >.item{
            margin: 4.5px 12px 4.5px 0;
            font-size: 17px;
        }
    }
}
.select-baidusug-cp{
    width: 100%;
    height: fit-content;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    position: relative;
    box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.211),0 1px 5px 0 rgba(0, 0, 0, 0.272);
    background-color: rgb(255, 255, 255);
    border-radius: 7px;
    overflow: hidden;
    border: 1px solid #eff1f4;
    >.container{
        width: 100%;
        box-sizing: border-box;
        height: fit-content;
        flex-wrap: wrap;
        display: flex;
        overflow-y: auto;
        >.item{
            line-height: 1.2;
            transition: all 0.2s;
            cursor: pointer;
            &:hover{
                color: #0077fa;
            }
        }
    }
    >.help{
        position: absolute;
        bottom: 0.5rem;
        right: 0.5rem;
        opacity: 0.5;
        font-size: 1.5rem;
        pointer-events: none;
    }
}
</style>

